<template>
  <div class="confirm-order-page">
    <!-- 顶部导航和步骤条 -->
    <div class="top-bar">
      <van-nav-bar
          title="确认订单"
          left-arrow
          @click-left="handleGoBack"
      />
      <div class="steps">
        <div class="step-item active">
          <div class="step-circle">1</div>
          <div class="step-text">确认订单</div>
        </div>
        <div class="step-divider"></div>
        <div class="step-item current">
          <div class="step-circle">2</div>
          <div class="step-text">支付</div>
        </div>
        <div class="step-divider"></div>
        <div class="step-item">
          <div class="step-circle">3</div>
          <div class="step-text">交易完成</div>
        </div>
      </div>
    </div>

    <!-- 购买商品模块、交易信息模块、价格详情模块保持不变 -->
    <!-- 购买商品模块 -->
    <div class="module-card">
      <h3 class="module-title">购买商品</h3>
      <div class="goods-info">
        <img
            class="goods-img"
            :src="parsedImages[0] || 'https://picsum.photos/80/80?random=1'"
            :alt="itemData.title || '商品图片'"
        />
        <div class="goods-desc">
          <div class="goods-name">{{ itemData.title || '加载中...' }}</div>
          <div class="goods-spec">
            {{ itemData.categories?.name || '未知分类' }} |
            {{ itemData.description || '无商品描述' }}
          </div>
          <div class="goods-price">¥{{ itemData.price || 0 }}</div>
        </div>
      </div>
    </div>

    <!-- 交易信息模块 -->
    <div class="module-card">
      <h3 class="module-title">交易信息</h3>
      <div class="trade-info">
        <div class="trade-item">
          <span class="trade-label">交易方式</span>
          <span class="trade-value">{{ itemData.type === 1 ? '出售' : '出租' }}</span>
        </div>
        <div class="trade-item">
          <span class="trade-label">交易地点</span>
          <span class="trade-value">
            {{ itemData.user?.building || '未知' }}号楼{{ itemData.user?.unit || '' }}单元
          </span>
        </div>
        <div class="trade-item">
          <span class="trade-label">交易时间</span>
          <span class="trade-value">协商确定</span>
        </div>
        <div class="trade-item">
          <span class="trade-label">卖家</span>
          <div class="trade-value seller-info">
            <img
                :src="itemData.user?.avatar || 'https://picsum.photos/24/24?random=2'"
                class="seller-avatar"
                :alt="itemData.user?.nickname || '卖家头像'"
            />
            {{ itemData.user?.nickname || '未知卖家' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 价格详情模块 -->
    <div class="module-card">
      <h3 class="module-title">价格详情</h3>
      <div class="price-info">
        <div class="price-item">
          <span class="price-label">商品价格</span>
          <span class="price-value">¥{{ itemData.price || 0 }}</span>
        </div>
        <div class="price-item">
          <span class="price-label">运费</span>
          <span class="price-value">¥0</span>
        </div>
        <div class="price-total">
          <span class="price-label">实付金额</span>
          <span class="price-value total">¥{{ calculateTotalPrice }}</span>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮区域 -->
    <div class="bottom-buttons">
      <van-button
          class="cancel-btn"
          type="default"
          @click="showCancelConfirm = true"
      >
        取消订单
      </van-button>
      <van-button
          class="pay-btn"
          type="danger"
          @click="handlePay"
      >
        立即支付 ¥{{ calculateTotalPrice }}
      </van-button>
    </div>

    <!-- 自定义确认弹窗 - 不依赖Dialog组件 -->
    <div v-if="showCancelConfirm" class="custom-confirm-mask">
      <div class="custom-confirm-dialog">
        <div class="confirm-title">取消订单</div>
        <div class="confirm-message">
          确定要取消该订单吗？取消后可在“我的订单”中重新操作
        </div>
        <div class="confirm-buttons">
          <button
              class="confirm-btn cancel"
              @click="showCancelConfirm = false"
          >
            取消
          </button>
          <button
              class="confirm-btn confirm"
              @click="confirmCancelOrder"
          >
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from '@/utils/axios.ts';
import { showToast } from 'vant'; // 只保留toast用于提示

const route = useRoute();
const router = useRouter();
const orderData = ref<any>({}); // 订单数据
const itemData = ref<any>({});  // 物品详情数据
const parsedImages = ref<string[]>([]); // 解析后的图片数组
const showCancelConfirm = ref(false); // 控制自定义弹窗显示

// 计算总价格
const calculateTotalPrice = computed(() => {
  return itemData.value.price || 0;
});

onMounted(() => {
  const orderId = route.query.orderId;
  if (orderId) {
    fetchOrderData(orderId);
  } else {
    showToast('订单ID缺失，无法获取订单信息');
  }
});

// 获取订单数据
const fetchOrderData = async (orderId: any) => {
  try {
    const res = await axios.post(`/api/itemOrders/getById?orderId=${orderId}`);
    if (res.code === 200 && res.data) {
      orderData.value = res.data;
      if (orderData.value.itemId) {
        await fetchItemData(orderData.value.itemId);
      }
    } else {
      showToast('获取订单信息失败');
    }
  } catch (error) {
    console.error('获取订单信息出错:', error);
    showToast('网络异常，获取订单信息失败');
  }
};

// 获取商品详情
const fetchItemData = async (itemId: any) => {
  try {
    const itemRes = await axios.post(`/api/userItems/getById?id=${itemId}`);
    itemData.value = itemRes;
    try {
      parsedImages.value = JSON.parse(itemData.value.images || '[]');
    } catch (e) {
      parsedImages.value = [];
      console.error('解析图片失败:', e);
    }
  } catch (err) {
    console.error('获取商品详情出错:', err);
    showToast('网络异常，无法加载商品信息');
  }
};

// 返回上一页
const handleGoBack = () => {
  router.back();
};

// 处理支付逻辑
const handlePay = () => {
  axios.post("/api/itemOrders/updateStaus?orderId="+route.query.orderId)
  router.push({
    path: '/paySuccess',
    query: {
      orderNumber: orderData.value.orderNumber,
      itemTitle: itemData.value.title,
      itemPrice: itemData.value.price,
      payMethod: '邻里钱包',
      payTime: new Date().toLocaleString(),
    },
  });
};

// 确认取消订单
const confirmCancelOrder = () => {
  // 隐藏弹窗
  showCancelConfirm.value = false;

  // 校验订单信息
  if (!orderData.value.orderId || !itemData.value.title) {
    showToast('订单信息未加载完整，无法取消');
    return;
  }

  // 跳转到取消支付页面
  router.push({
    path: '/PayCancel',
    query: {
      orderId: orderData.value.orderId,
      orderNumber: orderData.value.orderNumber || '未知订单',
      itemTitle: itemData.value.title,
      itemPrice: itemData.value.price || 0,
      from: 'confirmOrder'
    }
  });
};
</script>

<style scoped>
/* 原有样式保持不变 */
.confirm-order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
}

/* 省略中间原有样式... */

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  padding: 8px 16px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.cancel-btn, .pay-btn {
  flex: 1;
  height: 44px;
  border-radius: 22px;
  margin: 0 4px;
}

.cancel-btn {
  border: 1px solid #ddd;
}

.pay-btn {
  background-color: #ee0a24;
  color: #fff;
}

/* 自定义确认弹窗样式 */
.custom-confirm-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.custom-confirm-dialog {
  width: 85%;
  max-width: 300px;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px 15px;
}

.confirm-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 15px;
}

.confirm-message {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin-bottom: 20px;
  line-height: 1.5;
}

.confirm-buttons {
  display: flex;
  border-top: 1px solid #eee;
}

.confirm-btn {
  flex: 1;
  height: 44px;
  line-height: 44px;
  border: none;
  background: none;
  font-size: 16px;
  cursor: pointer;
}

.confirm-btn.cancel {
  color: #666;
  border-right: 1px solid #eee;
}

.confirm-btn.confirm {
  color: #ee0a24;
}

/* 补充原有样式 */
.top-bar {
  background-color: #fff;
  padding: 10px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.steps {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 10px;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-circle {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  margin-bottom: 4px;
}

.step-text {
  font-size: 12px;
}

.step-item.active .step-circle {
  background-color: #1989fa;
  color: #fff;
}

.step-item.active .step-text {
  color: #1989fa;
}

.step-item.current .step-circle {
  background-color: #1989fa;
  color: #fff;
}

.step-item.current .step-text {
  color: #1989fa;
}

.step-divider {
  flex: 1;
  height: 1px;
  background-color: #e5e5e5;
  margin: 0 8px;
}

.module-card {
  background-color: #fff;
  border-radius: 8px;
  margin: 10px 16px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.goods-info {
  display: flex;
  align-items: center;
}

.goods-img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
  background-color: #f5f5f5;
}

.goods-desc {
  flex: 1;
}

.goods-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 4px;
}

.goods-spec {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.goods-price {
  font-size: 14px;
  color: #ee0a24;
}

.trade-info .trade-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.trade-info .trade-item:last-child {
  margin-bottom: 0;
}

.trade-label {
  color: #666;
}

.trade-value {
  color: #333;
}

.seller-info {
  display: flex;
  align-items: center;
}

.seller-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 6px;
  object-fit: cover;
}

.price-info .price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.price-info .price-item:last-child {
  margin-bottom: 0;
}

.price-label {
  color: #666;
}

.price-value {
  color: #333;
}

.price-total {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.price-value.total {
  color: #ee0a24;
  font-weight: bold;
}
</style>
